<template>
  <div>
    <!-- <searchForm :searchArr="searchArr" @onSubmit="onSubmit"></searchForm> -->
    <div class="gva-table-box">
      <LTable tableName="masterBom" :pages="pages" :columns="columns" :tableData="tableData"
        @updateMultipleSelection="updateMultipleSelection" @changePages="changePages" :export="true"
        @rowDblclick="row => updateSbuProjectsFunc(row, 1)" :maxHeight="'calc(100vh - 226px)'" :searchArr="searchArr"
        :isSearch="true" @onSubmit="onSubmit">
        <template #action>
          <div class="gva-btn-list" v-if="userStore.userInfo.authority?.authorityId !== 1000">
            <el-button type="primary" icon="plus" @click="openDialog">新增</el-button>
            <el-button icon="delete" v-auth="btnAuth.batchDel" style="margin-left: 10px" :disabled="!multipleSelection.length"
              @click="onDelete">删除</el-button>
            <!-- <el-button
                :disabled="multipleSelection.length!=1"
                type="primary"
                icon="edit"
                class="table-button"
                @click="updateSbuProjectsFunc(multipleSelection.length==1&&multipleSelection[0])"
            >
                编辑
            </el-button> -->
            <el-button type="primary" class="table-button" :disabled="multipleSelection.length != 1"
              @click="historyVision(multipleSelection[0])">
              历史版本
            </el-button>
            <relatedBtn :disabled="multipleSelection.length != 1" :row="multipleSelection.length == 1 && multipleSelection[0]"
              :modalType="'masterBOM'" />
          </div>
        </template>
        <template #FirstCreatedAt="{ row }">
                    <span v-if="row.FirstCreatedAt">{{formatDate(row.FirstCreatedAt)=="1-01-01" ? '' : formatDate(row.FirstCreatedAt) }}</span>
                </template>
      </LTable>
      <el-dialog v-model="historyVisionShow" title="历史版本" width="900">
        <el-table ref="multipleTableRef" :data="historyList" @rowDblclick="rowDblclickFun" style="width: 100%">
          <el-table-column prop="styleNum" label="款式编号" />
          <el-table-column prop="localStyleNum" label="本廠款號" />
          <el-table-column prop="customerStyleNum" label="客款号" />
          <el-table-column prop="version" label="版本" />
          <el-table-column prop="CreatedAt" label="创建时间" />
        </el-table>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>

import {
  deleteMasterBOM,
  deleteMasterBOMByIds,
  getMasterBOMList,
  getMasterBomHistoryList
} from '@/api/plmMasterBOM'
import { useRoute, useRouter } from "vue-router";
// 全量引入格式化工具 请按需保留
import {
  getDictFunc,
  formatDate,
  formatBoolean,
  filterDict,
  ReturnArrImg,
  onDownloadFile,
} from "@/utils/format";
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, reactive, watch } from "vue";
// 引入组件
import LTable from "@/components/LTable/LTable.vue";
import { useUserStore } from "@/pinia/modules/user";
defineOptions({
  name: "masterBOM",
});

// 使用 useRoute 函数获取当前路由信息
const router = new useRouter();
const route = new useRoute();
const userStore = useUserStore();
import { useBtnAuth } from "@/utils/btnAuth";
const btnAuth = useBtnAuth();

// 自动化生成的字典（可能为空）以及字段
const formData = ref({
  productSpecNum: "",
  projectNum: "",
  cumstomerNum: "",
  customerStyleNum: "",
  updateUser: "",
  UpdatedAt: new Date(),
  status: "",
});

// 验证规则
const rule = reactive({});

const searchRule = reactive({
  createdAt: [
    {
      validator: (rule, value, callback) => {
        if (searchInfo.value.startCreatedAt && !searchInfo.value.endCreatedAt) {
          callback(new Error("请填写结束日期"));
        } else if (
          !searchInfo.value.startCreatedAt &&
          searchInfo.value.endCreatedAt
        ) {
          callback(new Error("请填写开始日期"));
        } else if (
          searchInfo.value.startCreatedAt &&
          searchInfo.value.endCreatedAt &&
          (searchInfo.value.startCreatedAt.getTime() ===
            searchInfo.value.endCreatedAt.getTime() ||
            searchInfo.value.startCreatedAt.getTime() >
            searchInfo.value.endCreatedAt.getTime())
        ) {
          callback(new Error("开始日期应当早于结束日期"));
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
});

const elFormRef = ref();
const elSearchFormRef = ref();

// =========== 表格控制部分 ===========
const tableData = ref([]);
const searchInfo = ref({});
const pages = ref({
  page: 1,
  pageSize: 20,
  total: 0,
});
// ======表格头部数据======
const columns = ref([
  // {
  //     prop: "masterBomNum",
  //     width: 200,
  //     label: "MasterBOM编号",
  //     show: true, // 通过 show 来控制列的展示或隐藏
  //   },
  {
    prop: "styleNum",
    label: "款式编号",
    fixedWidth: 130,
    show: true,
    filter: true,
    // slot: "styleNum",
    tableColumnProps: {
      fixed: "left",
    },
  },
  {
    prop: "localStyleNum",
    width: 130,
    label: "本厂款号",
    show: true,
  },
  {
    prop: "sbuNum",
    width: 130,
    label: "SBU",
    show: true,
  },
  {
    prop: "cumstomerNum",
    width: 130,
    label: "客户编号",
    show: true,
  },
  {
    prop: "customerStyleNum",
    width: 130,
    label: "客户款号",
    show: true,
  },
  {
    prop: "customerBrand",
    width: 130,
    label: "品牌",
    show: true,
  },

  {
    prop: "CreatedAt",
    width: 120,
    label: "创建时间",
    show: true, // 通过 show 来控制列的展示或隐藏
  },
  {
    prop: "UpdatedAt",
    width: 120,
    label: "更新时间",
    show: true,
  },
  {
    prop: "version",
    fixedWidth: 80,
    label: "版本",
    show: true,
  },
  {
    prop: "status",
    fixedWidth: 80,
    label: "状态",
    show: true,
  },
  {
    prop: "FirstCreatedAt",
    label:'第一版本创建时间',
    show: true,
    fixedWidth: 150,
    //  slot: "FirstCreatedAt",
    // tableColumnProps: {
    //     formatter: (row) => formatDate(row.FirstCreatedAt),
    //  },
  },
]);
// ======查询数据======
const searchArr = ref([
  // {
  //     prop: "masterBomNum",
  //     width: 200,
  //     label: "MasterBOM编号",
  //     show: true, // 通过 show 来控制列的展示或隐藏
  //     type:'input',
  //     value:'',
  //   },
  {
    prop: "styleNum",
    width: 200,
    label: "款式编号",
    show: true, // 通过 show 来控制列的展示或隐藏
    type: 'input',
    value: '',
  },
  {
    prop: "localStyleNum",
    width: 130,
    label: "本厂款号",
    show: true,
    type: 'input',
    value: '',
  },
  {
    prop: "sbuNum",
    width: 130,
    label: "SBU",
    show: true,
    type: 'input',
    value: '',
  },
  {
    prop: "cumstomerNum",
    width: 200,
    label: "客户编号",
    show: true,
    type: 'input',
    value: '',
  },
  {
    prop: "customerStyleNum",
    width: 200,
    label: "客户款号",
    show: true,
    type: 'input',
    value: '',
  },
  {
    prop: "customerBrand",
    width: 130,
    label: "品牌",
    show: true,
    type: 'input',
    value: '',
  },

  {
    prop: "CreatedAt",
    width: 200,
    label: "创建时间",
    show: true, // 通过 show 来控制列的展示或隐藏
    value: '',
    type: 'datetimerange',
  },
  {
    prop: "UpdatedAt",
    width: 200,
    label: "更新时间",
    show: true,
    value: '',
    type: 'datetimerange',
  },
  {
    prop: "status",
    width: 200,
    label: "状态",
    type: 'select',
    selectList: [{ value: '草稿', label: '草稿' }, { value: '已確認', label: '已確認' }, { value: '已匯入SAP', label: '已匯入SAP' }],
    value: '',
    show: true,
  },
  {
    prop: "version",
    fixedWidth: 80,
    label: "版本",
    show: true,
    type: 'input',
    value: '',
  },
    {
      prop: "FirstCreatedAt",
      label: "第一版创建时间",
      show: true, // 通过 show 来控制列的展示或隐藏
      value: "",
      type: "datetimerange",
    },

]);

// 搜索
const onSubmit = (params) => {


  searchInfo.value = {
    ...params
  }
  // if (params.length) {

  // if (searchInfo.value.CreatedAt.length) {
  //   searchInfo.value.startCreatedAt = formatDate(
  //     searchInfo.value.CreatedAt[0]
  //   );
  //   searchInfo.value.endCreatedAt = formatDate(searchInfo.value.CreatedAt[1]);
  // delete searchInfo.value.CreatedAt;
  //   }
  // } else {
  //   searchInfo.value = {};
  // }
  pages.value.page = 1;
  pages.value.pageSize = 20;
  getTableData();
};

// 改变页码
function changePages(currentPages) {
  console.log("currentPages=============", currentPages);
  pages.value = {
    ...pages.value,
    ...currentPages,
  };
  getTableData();
}


// 查询
const getTableData = async () => {
  const table = await getMasterBOMList({
    page: pages.value.page,
    pageSize: pages.value.pageSize,
    ...searchInfo.value,
  });
  if (table.code === 0) {
    tableData.value = table.data.list;
    tableData.value.forEach((item) => {
      item.CreatedAt = item.CreatedAt ? formatDate(item.CreatedAt) : "";
      item.UpdatedAt = item.UpdatedAt ? formatDate(item.UpdatedAt) : "";
      item.FirstCreatedAt = formatDate(item.FirstCreatedAt)=="1-01-01" ? "" : formatDate(item.FirstCreatedAt);
      item.customerDemandDate = item.customerDemandDate ? formatDate(item.customerDemandDate) : "";
      item.piDemandDate = item.piDemandDate ? formatDate(item.piDemandDate) : "";
    });
    pages.value.total = table.data.total;
    pages.value.page = table.data.page;
    pages.value.pageSize = table.data.pageSize;
  }
};

// getTableData();

// ============== 表格控制部分结束 ===============

// 获取需要的字典 可能为空 按需保留
const setOptions = async () => { };

// 获取需要的字典 可能为空 按需保留
setOptions();

// 多选数据
const multipleSelection = ref([]);
// 多选
const updateMultipleSelection = (val) => {
  multipleSelection.value = val;
};

// 删除行
const deleteRow = (row) => {
  ElMessageBox.confirm("确定要删除吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deleteMasterBOMFunc(row);
  });
};

// 多选删除
const onDelete = async () => {
  ElMessageBox.confirm("确定要删除吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const IDs = [];
    if (multipleSelection.value.length === 0) {
      ElMessage({
        type: "warning",
        message: "请选择要删除的数据",
      });
      return;
    }
    multipleSelection.value &&
      multipleSelection.value.map((item) => {
        IDs.push(item.ID);
      });
    const res = await deleteMasterBOMByIds({ IDs });
    if (res.code === 0) {
      ElMessage({
        type: "success",
        message: "删除成功",
      });
      if (tableData.value.length === IDs.length && pages.value.page > 1) {
        pages.value.page--;
      }
      getTableData();
    }
  });
};

// 删除行
const deleteMasterBOMFunc = async (row) => {
  const res = await deleteMasterBOM({ ID: row.ID });
  if (res.code === 0) {
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    if (tableData.value.length === 1 && pages.value.page > 1) {
      pages.value.page--;
    }
    getTableData();
  }
};

function detailSbuProjectsFunc(params) {
  console.log(params);
}

// 打开弹窗
const openDialog = () => {
  console.log(123);
  router.push({
    path: "/layout/masterBOMAdd",
  });
};

function updateSbuProjectsFunc(datas, isView = 0) {
  router.push({
    path: `/layout/masterBOMAdd`,
    query: { masterBomNum: datas.masterBomNum, ID: datas.ID, subTitle: datas.localStyleNum, isView, dataTime: new Date().getTime() },
  });
}

// 历史版本shou
const historyVisionShow = ref(false);
let historyList = ref([]); // 历史版本数据
// 历史版本
const historyVision = (datas) => {
  historyList.value = [];
  let sel = multipleSelection.value[0];
  historyVisionShow.value = true;
  getMasterBomHistoryList({ masterBomNum: datas.masterBomNum }).then((res) => {
    if (res.code == 0) {
      historyList.value = res.data.list;
      historyList.value.forEach((item,index) => {
      item.CreatedAt = item.CreatedAt ? formatDate(item.CreatedAt) : "";
      item.index=index
    });
    }
  });
};
const rowDblclickFun = (row, column) => {
  historyVisionShow.value = false;
  if(row.ID == historyList.value[0].ID){
    router.push({
      path: `/layout/masterBOMAdd`,
      query: { masterBomNum: row.masterBomNum, ID: row.ID, subTitle: row.localStyleNum, isView:1 },
    });
  }else{
    router.push({
      path: `/layout/masterBOMAdd`,
      query: { masterBomNum: row.masterBomNum, ID: row.ID, subTitle: row.localStyleNum, isView:1,version:row.version||'暂无', isBigVersion:row.index === 0 ? 1 : 0 },
    });
  }
};

watch(() => route.path, (newPath, oldPath) => {
//   console.log('路由已变更：', `从 ${oldPath} 到 ${newPath}`);
    if(newPath == '/layout/masterBOM'){
        getTableData();
    }
},{immediate:true});

</script>

<style lang="scss" scoped>
@import url("@/style/common/common.scss");
</style>
